package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    //从调度服务器获取，一个目标存储服务器，上传
    @Autowired
    private FastFileStorageClient client;

    // 获取存储服务器的请求URL
    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private VideoApi videoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;

    /**
     * 上传视频
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //判断是否传来数据
        if (StringUtils.isEmpty(videoThumbnail) || StringUtils.isEmpty(videoFile)){
            throw new BusinessException(ErrorResult.error());
        }
        //都不为空
        //1.先存储视频到fastFDS服务中
        String filename = videoFile.getOriginalFilename();
        String filenameSuffix = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath path = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filenameSuffix, null);
        //获取上传视频路径
        String videoUrl = webServer.getWebServerUrl() + path.getFullPath();
        //将视频封面图片存入oss中
        String imageUrl = ossTemplate.uploadVideoThumbnail(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream(), UserHolder.getUserId());
        //构造对象调用API存入数据
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setVideoUrl(videoUrl);
        video.setPicUrl(imageUrl);
        video.setText("心脏撒撒该哟");
        video.setCreated(System.currentTimeMillis());
        String videoId = videoApi.saveVideo(video);
        if (StringUtils.isEmpty(videoId)){
            throw  new BusinessException(ErrorResult.error());
        }
    }

    /**
     * 小视频列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult tabulationVideo(int page, int pagesize) {
        //查询redis中缓存的推荐视频id
        String key = Constants.VIDEOS_RECOMMEND+UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);
        //判断redis中是否有数据
        List<Video> list = new ArrayList<>();
        int count = 0;
        if (!StringUtils.isEmpty(value)){
            //redis中有数据,查询
            String[] values = value.split(",");
            if ( (page-1) * pagesize < values.length){
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(item -> Long.valueOf(item)).collect(Collectors.toList());
                //调用API查询vids视频数据
                list = videoApi.findRedisVids(vids);
            }
            count = PageUtil.totalPage(values.length,pagesize);
        }
        //不存在数据到数据库中查询
        if (CollUtil.isEmpty(list)){
            list = videoApi.findVideo(page-count,pagesize);
        }
        //获取集合中的用户id
        List<Long> ids = list.stream().map(item -> item.getUserId()).collect(Collectors.toList());
        //调用API查询数据
        Map<Long, UserInfo> map = userInfoApi.findByIds(null, ids);

        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo userInfo = map.get(video.getUserId());
            if (userInfo != null){
                VideoVo vo = VideoVo.init(userInfo, video);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0,vos);
    }
}
